﻿using System;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc;

namespace Panorama.Web.Controllers
{
    public class HomeController : BaseController
    {
        [AllowAnonymous]
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Content");
            }

            // add model Error to ModelState from Account/Login redirection.
            // There is a better way but no time to fix it !
            AddErrorsToModelState();

            return View();
        }
  
        [Authorize]
        public ActionResult Content()
        {
            ViewBag.NavigationName = ViewResources.Layout.Title;

            if (!SiteMapManager.SiteMaps.ContainsKey("sample"))
            {
                SiteMapManager.SiteMaps.Register<XmlSiteMap>("sample", sitmap => sitmap.LoadFrom("~/sample.sitemap"));
            }
           
            return View();
        }

        [AllowAnonymous]
        public ActionResult ChangeCulture(string lang, string returnUrl)
        {
            Session["Culture"] = new CultureInfo(lang);
            return Redirect(returnUrl);
        }

        #region Helpers

        private void AddErrorsToModelState()
        {
            // add model Error to ModelState from Account/Login redirection.
            // There is a better way but no time to fix it !
            if (TempData["Errors"] != null)
            {
                var errors = TempData["Errors"] as ModelStateDictionary;

                foreach (var err in errors)
                {
                    var allErrors = err.Value.Errors.Select(e => e.ErrorMessage).ToList();

                    foreach (var val in allErrors)
                    {
                        ModelState.AddModelError("", val.ToString());
                    }
                }

                TempData["Errors"] = null;
            }
        }
        
        #endregion
    }
}